<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
        <link rel="stylesheet" type="text/css" href="css/init.css" />
        <link rel="stylesheet" type="text/css" href="css/style.css" />
        <!-- 引入样式文件 -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vant@2.12/lib/index.css"/>
        
    </head>
    <body>
        <div id="app">
        </div>
        
        <!-- <div class="beecloud-pay-close" onclick="close()"></div> -->
    </body>
    <script type="text/javascript" src="js/vue.min.js"></script>
    <script type="text/javascript" src="js/axios.min.js"></script>
    <script type="text/javascript" src="js/request.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src="js/vant.min.js"></script>
    <!-- <script src="http://res2.wx.qq.com/open/js/jweixin-1.6.0.js"></script> -->
    <script type="text/javascript" src="js/alipayjsapi.inc.min.js"></script>
    <script type="text/javascript">
        let app = new Vue({
            el:'#app',
            data:function(){
                return {
                    title:'哆啦外教网',
                    price:'',// 获取加密的价格，用于接口传参、
                    showPrice:'', // 页面显示的价格
                    payShow:false,
                    payListShow:false,
                    isweixin:false, // 是否为微信浏览器打开的
                    ismobile:false, // 是否为手机端
                    wxPayShow:false, // 微信支付二维码显示
                    code:'',
                    time:0,
                    openId:'',
                    payhtml:'',
                    mobile:"",
                    clickid:""
                }
            },
            template:`<div>
                        <div class="pay-wrap">
                                <div class="pay-bg"></div>
                                <div class="pay-head">
                                    <img class="pay-head-icon" src="./img/icon_more_0910.png" alt="/">
                                    <div class="pay-head-text">
                                        <h3>待支付</h3>
                                        <p>订单已提交，请尽快完成支付.</p>
                                    </div>
                                </div>
                                <div class="pay-content">
                                    <img class="yt-logo" src="./img/logo.jpg?v=1" alt="">
                                    <h3 class="yt-logo-text">{{title}}</h3>
                                    <!-- <img class="yt-logo-text" src="./image/icon_fonts_0910.png" alt=""> -->
                                    <p class="pay-content-text">
                                        <span class="pay-countText">总计</span>
                                        <span class="pay-icon">￥</span>
                                        <span id="pay-money" class="pay-money">{{showPrice}}</span>
                                    </p>
                                    <div v-html="payhtml"></div>
                                    <button class="pay-btn" :class="openId||code||!isweixin?'success-btn':'disable-btn'" :disabled="openId||code||!isweixin?false:true" @click="submit">确认支付</button>
                                </div>           
                            </div>
                            <div id="beecloud-pay" class="open" v-show="payShow">
                                <div class="beecloud-wx" v-if="wxPayShow"><canvas width="250" height="250"></canvas><div class="beecloud-pay-close" @click="closeWxPay"></div></div>
                            </div>
                            <ul id="beecloud-pay-list" v-show="payListShow">
                                <li class="beecloud-pay-btn channel-ali" ref="J_btn" @click="alipayEvent">
                                    <i></i><span>支付宝支付</span>
                                </li>
                                <li class="beecloud-pay-btn channel-wxmp" @click="wxPay">
                                    <i></i><span>微信支付</span>
                                </li>
                                <div class="beecloud-pay-close" @click="close"></div>
                            </ul>
                        </div>`,


            mounted() {
                // this.$refs.J_btn.addEventListener('click',this.alipayEvent);
            },
            methods:{
                searchCode(){
                    if(getUrlParam('code')){
                        this.code = getUrlParam('code');
                        this.time = 0;
                    }else{
                        if(this.time < 3){
                            this.getCode();
                        }
                    }
                },
                getCode(){                   
                    let url = encodeURIComponent(`http://pay.dorakr.com/?money=${this.showPrice}&mobile=${this.mobile}&clickid=${this.clickid}`);
                    window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx04cdf6563c0c8d67&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;                    
                    this.time += 1;
                    this.searchCode();
                },
                isWX() {
                    if(isWeiXin()){
                        this.isweixin=true;                       
                    }else{
                        this.isweixin=false;
                    }
                },
                insertLog(){
                    let newParams = {
                            mobile:getUrlParam("mobile"),
                            type: 4
                        };

                        request.post('/address/updateData', newParams).then((res) =>{
                            console.log(res);                            
                        }).catch((err) => {
                            console.log(err);
                        });
                },
                submit() {
                    // 手机端,微信浏览器支付，直接跳微信支付接口
                    //  if(this.ismobile){
                    //      if(this.isweixin){
                    //         this.wxPayOrder();
                    //      }else{ // 支付宝支付
                    //          this.alipayEvent()
                    // }
                        
                    // }else{ // pc端，显示微信和支付宝支付链接
                    //     this.payShow = true;
                    //     this.payListShow = true;
                    // }
                    
                    // if(this.isweixin){
                    //     this.wxPayOrder();
                    // }else{
                        this.payShow = true;
                        this.payListShow = true;
                    // }

                      this.insertLog();
                },
                // 微信支付点击事件
                wxPay() {
                    if(!this.ismobile){
                        // this.wxPayShow = true; // pc端微信支付生成支付二维码
                        // this.payListShow = false;
                    }else{
                        // this.wxPayOrder(); //手机端调微信支付接口
                        if(this.isweixin){
                            this.wxPayOrder();
                        }else{
                            vant.Toast('请用微信浏览器打开!')
                            this.close();
                        }
                        
                    }
                    
                },
                close() {
                    this.payShow = false;
                    this.payListShow = false;
                },
                closeWxPay() {
                    this.payShow = false;
                    this.wxPayShow = false
                },
                
                // 支付宝支付
                alipayEvent() {
                    /*ap.tradePay({
                        orderStr: 'timestamp=2016-12-27%2018%3A00%3A00&method=alipay.trade.app.pay&app_id=2014073000007292......'
                    }, function(res){
                        ap.alert(res.resultCode);
                    });*/
                    
                    let newParams = {
                            type:'alipay',
                            money: this.showPrice
                        };

                    request.post('/wechat/pay/index', newParams).then((res) =>{
                            console.log(res);
                            
                            this.payhtml = res.res.data;
                            this.$nextTick(()=> {					
                                document.forms[0].submit();			//自动执行表单提交事件
                            })
                            // const div = document.createElement('div');
                            // div.innerHTML = (res.res.data);  //res.data是返回的表单
                            // document.body.appendChild(div);
                        }).catch((err) => {
                            console.log(err);
                        })

                },
                
                // 微信支付
                wxPayOrder() {
                    if(this.openId || this.code){
                        let oldparams = {
                            type:'wx',
                            money: this.showPrice
                        };
                        let obj = this.openId ? {open_id:this.openId}:{code:this.code}
                        let newParams = Object.assign(oldparams,obj);
                                            
                        request.post('/wechat/pay/index', newParams).then((res) =>{
                            console.log(res);
                            if(res.code === 2000) {
                                const pay_params = res.data
                                let openid = res.data.open_id || '';
                                window.localStorage.setItem('open_id',openid);
                                if (typeof WeixinJSBridge === "undefined"){
                                    if(document.addEventListener){
                                        document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false);
                                    }else if (document.attachEvent){
                                        document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady);
                                        document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady);
                                    }
                                }else{
                                    this.onBridgeReady(pay_params);
                                }
                            }else{
                                // alert(res.code)
                                // alert(res.msg)
                                // alert(res.data)
                                vant.Toast.fail('微信支付调起失败！');
                                
                            }
                        }).catch((err) => {
                            console.log(err);
                        })
                    }
                    
                },
                onBridgeReady(params) {
                    var that = this
                    WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', {
                        "appId": params.appId,  //公众号名称，由商户传入
                        "timeStamp": String(params.timeStamp), //支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                        "nonceStr": params.nonceStr,  //支付签名随机串，不长于 32 位
                        "package": params.package,//统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
                        "signType": 'MD5',  //签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                        "paySign": params.paySign, //支付签名
                    },
                    function (res) {
                        if (res.err_msg === "get_brand_wcpay_request:ok") {
                            window.location.replace(`paySuccess.html?order_id=${params.order_id}&mobile=${that.mobile}&clickid=${that.clickid}`);
                            vant.Toast.success('支付成功！');
                        } else if (res.err_msg === "get_brand_wcpay_request:fail") {
                            vant.Toast.fail('支付失败！');
                        }
                    });
                }
            },
            // beforeDestroy() {
            //     this.$refs.J_btn.removeEventListener('click',this.alipayEvent);
            // },
            created (){
                if(isMobile()){
                    this.ismobile = true;
                    this.isWX();
                }else{
                    this.ismobile = false;
                    this.isWX();
                }               
                //this.price = this.getUrlParam("token");
                let price = getUrlParam("money");

                this.mobile = getUrlParam("mobile");
                this.clickid = getUrlParam("clickid");

                
                if(!price || !isNumber(price))
                {
                    vant.Toast.fail('金额参数有误');return;
                }
                this.showPrice = price;
                this.code = '';
                // this.getCode();
                if(this.isweixin){
                    this.openId = window.localStorage.getItem('open_id');
                    if(!this.openId){
                        this.searchCode();
                    }
                    
                }
                
            },

        });
    </script>
</html>